<template>
  <div class="apple-notifications-container">
    <div class="apple-page-header glass-effect">
      <h1>消息通知</h1>
      <div class="header-actions">
        <button class="apple-button apple-button-primary button-float" @click="markAllAsRead"
          :disabled="unreadNotifications.length === 0">
          全部标为已读
        </button>
        <button class="apple-button button-float" @click="openSettings">
          通知设置
        </button>
      </div>
    </div>

    <div class="apple-tab-container">
      <div class="apple-tabs">
        <div class="apple-tab" :class="{ active: activeTab === 'unread' }" @click="activeTab = 'unread'">
          未读通知
          <div v-if="unreadNotifications.length > 0" class="tab-badge">
            {{ unreadNotifications.length }}
          </div>
        </div>
        <div class="apple-tab" :class="{ active: activeTab === 'all' }" @click="activeTab = 'all'">
          用户状态
        </div>
        <div class="apple-tab" :class="{ active: activeTab === 'recent' }" @click="activeTab = 'recent'">
          最近操作
        </div>
      </div>

      <div class="apple-tab-content glass-effect">
        <div v-if="activeTab === 'unread'" class="tab-pane">
          <div v-if="unreadNotifications.length === 0" class="empty-state">
            <div class="empty-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
                <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
              </svg>
            </div>
            <p class="empty-message">暂无未读通知</p>
          </div>
          <notification-list v-else :notifications="unreadNotifications" @mark-read="markAsRead" apple-style="true" />
        </div>

        <div v-if="activeTab === 'all'" class="tab-pane">
          <div v-if="allNotifications.length === 0" class="empty-state">
            <div class="empty-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
                <path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
              </svg>
            </div>
            <p class="empty-message">暂无用户状态通知</p>
          </div>
          <notification-list v-else :notifications="allNotifications" @mark-read="markAsRead" apple-style="true" />
        </div>

        <!-- 新增最近操作选项卡内容 -->
        <div v-if="activeTab === 'recent'" class="tab-pane">
          <div v-if="recentActivities.length === 0" class="empty-state">
            <div class="empty-icon">
              <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
                <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
            </div>
            <p class="empty-message">暂无最近操作记录</p>
          </div>
          <recent-activity-list v-else :activities="recentActivities" @mark-read="markAsRead" apple-style="true" />
        </div>
      </div>
    </div>

    <!-- 通知设置对话框 -->
    <div class="apple-modal" v-if="settingsVisible">
      <div class="modal-overlay" @click="settingsVisible = false"></div>
      <div class="modal-container glass-effect">
        <div class="modal-header">
          <h2>通知设置</h2>
          <button class="close-button" @click="settingsVisible = false">
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
              stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <div class="settings-section">
            <h3>接收通知类型</h3>
            <div class="settings-options">
              <label class="apple-checkbox">
                <input type="checkbox" v-model="notificationSettings.types" value="system">
                <span class="checkbox-label">系统通知</span>
              </label>
              <label class="apple-checkbox">
                <input type="checkbox" v-model="notificationSettings.types" value="inventory">
                <span class="checkbox-label">物品库存提醒</span>
              </label>
              <label class="apple-checkbox">
                <input type="checkbox" v-model="notificationSettings.types" value="expiry">
                <span class="checkbox-label">物品过期提醒</span>
              </label>
              <label class="apple-checkbox">
                <input type="checkbox" v-model="notificationSettings.types" value="updates">
                <span class="checkbox-label">系统更新通知</span>
              </label>
            </div>
          </div>

          <div class="settings-section">
            <h3>通知方式</h3>
            <div class="settings-options">
              <label class="apple-checkbox">
                <input type="checkbox" v-model="notificationSettings.methods" value="app">
                <span class="checkbox-label">应用内提醒</span>
              </label>
              <label class="apple-checkbox">
                <input type="checkbox" v-model="notificationSettings.methods" value="email">
                <span class="checkbox-label">邮件通知</span>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="apple-button" @click="settingsVisible = false">取消</button>
          <button class="apple-button apple-button-primary button-float" @click="saveSettings">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import NotificationList from '../components/notification/NotificationList.vue'
import RecentActivityList from '../components/notification/RecentActivityList.vue'
import { useNotificationStore } from '../stores/notification'
import { useActivityStore } from '../stores/activity'
import { useUserStore } from '../stores/user'
import { usePermissionStore } from '../stores/permission'
import { messagesApi } from '../utils/apiService'
import { useRouter } from 'vue-router'

// 使用权限store
const permissionStore = usePermissionStore()
// 使用通知store (仅用于保存设置)
const notificationStore = useNotificationStore()
// 使用活动store (仅用于结构化处理)
const activityStore = useActivityStore()

// 状态变量
const activeTab = ref('unread')
const settingsVisible = ref(false)
const notificationSettings = ref({
  types: [...notificationStore.settings.types],
  methods: [...notificationStore.settings.methods]
})

// 调试状态变量
const showDebugControls = ref(false) // 不显示调试控制区

// 本地消息数据
const allMessages = ref([])
const loading = ref(false)

// 计算属性 - 分类数据
const unreadNotifications = computed(() => {
  console.log('计算未读通知，数据源长度:', allMessages.value.length);
  return allMessages.value
    .filter(msg => {
      // 检查messageType和subType字段，兼容不同命名格式
      const msgType = msg.messageType || msg.message_type;
      const subType = msg.subType || msg.sub_type;
      const isRead = msg.isRead !== undefined ? msg.isRead : (msg.is_read !== undefined ? msg.is_read : null);
      
      console.log(`消息 ID:${msg.id}, 类型:${msgType}, 子类型:${subType}, 已读状态:${isRead}`);
      
      // 如果是通知类型且未读
      const isNotification = msgType === 'notification';
      const validSubType = ['system', 'inventory', 'expiry', 'updates', 'login', 'permission'].includes(subType);
      const isUnread = isRead === 0 || isRead === false;
      
      return isNotification && validSubType && isUnread;
    })
    .map(item => ({
      id: item.id,
      title: item.title,
      content: item.content,
      type: item.subType || item.sub_type,
      time: item.createTime || item.create_time,
      read: false,
      priority: item.priority,
      locationId: item.locationId || item.location_id,
      locationName: item.locationName || item.location_name || '',
      itemId: item.itemId || item.item_id,
      itemName: item.itemName || item.item_name || '',
      userId: item.userId || item.user_id,
      sourceUserId: item.sourceUserId
    }))
    .sort((a, b) => new Date(b.time) - new Date(a.time))
})

const allNotifications = computed(() => {
  console.log('计算全部通知，数据源长度:', allMessages.value.length);
  return allMessages.value
    .filter(msg => {
      // 检查messageType和subType字段，兼容不同命名格式
      const msgType = msg.messageType || msg.message_type;
      const subType = msg.subType || msg.sub_type;
      
      // 只显示用户状态相关的通知（登录、登出、权限变更）
      const isNotification = msgType === 'notification';
      const isUserStatusNotification = ['login', 'logout', 'permission'].includes(subType);
      
      return isNotification && isUserStatusNotification;
    })
    .map(item => ({
      id: item.id,
      title: item.title,
      content: item.content,
      type: item.subType || item.sub_type,
      time: item.createTime || item.create_time,
      read: (item.isRead === 1) || (item.is_read === 1) || (item.isRead === true) || (item.is_read === true),
      priority: item.priority,
      locationId: item.locationId || item.location_id,
      locationName: item.locationName || item.location_name || '',
      itemId: item.itemId || item.item_id,
      itemName: item.itemName || item.item_name || '',
      userId: item.userId || item.user_id,
      sourceUserId: item.sourceUserId
    }))
    .sort((a, b) => new Date(b.time) - new Date(a.time))
})

const recentActivities = computed(() => {
  console.log('计算最近活动，数据源长度:', allMessages.value.length);
  const activities = allMessages.value
    .filter(msg => {
      // 检查消息是否有有效ID
      if (!msg.id) {
        console.warn('发现没有ID的消息，将被过滤掉:', msg);
        return false;
      }
      
      // 检查messageType和subType字段，兼容不同命名格式
      const msgType = msg.messageType || msg.message_type;
      const subType = msg.subType || msg.sub_type;
      
      // 只显示活动类型消息，不再包含notification类型
      const isActivityMessage =
        msgType === 'activity' &&
        ['create', 'update', 'delete', 'move', 'login', 'logout', 'permission'].includes(subType);

      return isActivityMessage;
    })
    .map(item => ({
      id: item.id,
      title: item.title,
      content: item.content,
      actionType: item.subType || item.sub_type,
      time: item.createTime || item.create_time,
      userName: item.userName || item.user_name || (item.sourceUserId ? '用户' : '系统'),
      locationName: item.locationName || item.location_name || '',
      userId: item.userId || item.user_id,
      sourceUserId: item.sourceUserId,
      locationId: item.locationId || item.location_id,
      itemId: item.itemId || item.item_id,
      itemName: item.itemName || item.item_name || '',
      priority: item.priority,
      read: (item.isRead === 1) || (item.is_read === 1) || (item.isRead === true) || (item.is_read === true)
    }))
    .sort((a, b) => new Date(b.time) - new Date(a.time));

  console.log('计算出的活动数据:', activities);
  return activities;
})

// 监听标签切换，无需额外刷新数据
watch(activeTab, (newTab) => {
  console.log('标签切换为:', newTab);
})

// 方法
const markAsRead = async (id) => {
  if (!id) {
    console.error('尝试标记消息为已读，但消息ID为空');
    ElMessage.error('无法标记为已读：消息ID无效');
    return false;
  }

  console.log(`尝试标记消息ID为 ${id} 的消息为已读`);
  
  try {
    const response = await messagesApi.markAsRead(id);
    console.log(`标记已读响应:`, response);
    
    if (response && response.code === 200) {
      // 更新本地数据的已读状态
      const message = allMessages.value.find(msg => msg.id === id);
      if (message) {
        message.isRead = 1;
        console.log(`成功将消息ID ${id} 标记为已读`);
        ElMessage.success('已标记为已读');
      } else {
        console.warn(`标记成功，但未找到消息ID为 ${id} 的本地消息`);
      }
      return true;
    } else {
      console.warn('标记通知已读失败:', response);
      ElMessage.error('标记已读失败：' + (response?.msg || '服务器错误'));
      return false;
    }
  } catch (error) {
    console.error('标记通知已读出错:', error);
    ElMessage.error('标记已读失败：' + (error.message || '未知错误'));
    return false;
  }
}

const markAllAsRead = async () => {
  const locationId = getFirstLocationId();
  
  if (!locationId) {
    ElMessage.warning('无法获取位置ID，无法标记已读');
    return;
  }
  
  try {
    const response = await messagesApi.markAllAsRead(null, locationId);
    if (response && response.code === 200) {
      // 更新所有消息为已读状态
      allMessages.value.forEach(msg => {
        // 同时处理通知和活动类型的消息
        if (msg.messageType === 'notification' || msg.messageType === 'activity') {
          msg.isRead = 1;
        }
      });
      ElMessage.success('已将所有消息标记为已读');
    } else {
      ElMessage.error('标记已读失败');
    }
  } catch (error) {
    console.error('标记所有消息为已读失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
}

const openSettings = () => {
  settingsVisible.value = true
}

const saveSettings = async () => {
  const locationId = getFirstLocationId();
  
  if (!locationId) {
    ElMessage.warning('无法获取位置ID，无法保存设置');
    return;
  }
  
  try {
    const response = await messagesApi.updateLocationSettings(locationId, {
      notification_settings: {
        types: [...notificationSettings.value.types],
        methods: [...notificationSettings.value.methods]
      }
    });
    
    if (response && response.code === 200) {
      ElMessage.success('通知设置已保存');
      settingsVisible.value = false;
    } else {
      ElMessage.error('保存设置失败');
    }
  } catch (error) {
    console.error('保存通知设置失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
}

const router = useRouter()

onMounted(async () => {
  console.log('通知组件挂载开始');
  try {
    // 加载位置权限
    await permissionStore.loadUserLocationPermissions();
    
    // 加载所有消息数据
    console.log('开始加载消息数据...');
    await fetchAllMessages();
    console.log('消息数据加载完成');
    
    // 加载通知设置
    await fetchSettings();
    
    // 检查路由中是否有tab参数，如果有，切换到对应的标签页
    const route = router.currentRoute.value;
    if (route.query.tab) {
      const tabName = route.query.tab;
      if (['unread', 'all', 'recent'].includes(tabName)) {
        activeTab.value = tabName;
        console.log(`根据路由参数切换到"${tabName}"标签页`);
      }
    }
  } catch (error) {
    console.error('通知组件挂载时发生错误:', error);
    ElMessage.error('加载消息数据失败，请刷新页面重试');
  }
  console.log('通知组件挂载完成');
})

// 获取用户第一个有权限的位置ID
const getFirstLocationId = () => {
  // 1. 首先尝试从localStorage获取当前选择的位置ID
  const currentLocationId = localStorage.getItem('currentLocationId');
  if (currentLocationId) {
    console.log('从localStorage获取到当前位置ID:', currentLocationId);
    return currentLocationId;
  }
  
  // 2. 如果没有localStorage中的ID，再使用权限store中的第一个位置
  const userLocations = permissionStore.userLocationPermissions;
  
  if (!userLocations || Object.keys(userLocations).length === 0) {
    console.warn('用户没有位置权限');
    return null;
  }

  const firstLocationId = Object.keys(userLocations)[0];
  console.log('使用权限列表中的第一个位置ID:', firstLocationId);
  return firstLocationId;
}

// 获取所有消息数据（不分页）
const fetchAllMessages = async () => {
  const locationId = getFirstLocationId();
  
  if (!locationId) {
    console.error('无法获取位置ID，无法加载消息数据');
    ElMessage.error('无法获取位置ID，请检查权限');
    return false;
  }

  loading.value = true;

  try {
    console.log(`正在获取位置 ${locationId} 的所有消息数据...`);

    const response = await messagesApi.getMessages({
      locationId: locationId,
      getAllData: true // 使用新参数获取所有数据
    });

    console.log('原始消息响应数据:', JSON.stringify(response));

    if (response && response.code === 200 && response.data) {
      // 如果服务器返回的是data.list数组
      if (Array.isArray(response.data.list)) {
        allMessages.value = response.data.list;
      } 
      // 如果服务器直接返回data作为数组
      else if (Array.isArray(response.data)) {
        allMessages.value = response.data;
      }
      // 如果返回的格式与上述都不匹配
      else {
        console.error('消息数据格式不符合预期:', response.data);
        allMessages.value = [];
      }
      
      console.log('处理后的消息数据:', allMessages.value);
      
      // 数据类型统计
      const stats = {
        notification: 0,
        activity: 0,
        unread: 0
      };
      
      // 检查每条消息的关键字段，确保前端能正确识别
      allMessages.value.forEach((msg, index) => {
        console.log(`消息[${index}]:`, msg);
        
        // 适配后端字段名
        // 如果使用了snake_case而不是camelCase，进行转换
        if (msg.message_type && !msg.messageType) {
          msg.messageType = msg.message_type;
        }
        
        if (msg.sub_type && !msg.subType) {
          msg.subType = msg.sub_type;
        }
        
        if (msg.is_read !== undefined && msg.isRead === undefined) {
          msg.isRead = msg.is_read;
        }
        
        if (msg.create_time && !msg.createTime) {
          msg.createTime = msg.create_time;
        }

        // 统计各类型消息数量
        if (msg.messageType === 'notification') {
          stats.notification++;
          if (msg.isRead === 0) stats.unread++;
        }
        if (msg.messageType === 'activity') stats.activity++;
      });
      
      console.log('消息数据统计:', stats);
      console.log('未读通知:', unreadNotifications.value.length);
      console.log('全部通知:', allNotifications.value.length);
      console.log('最近活动:', recentActivities.value.length);
      
      return true;
    } else {
      console.warn('获取消息数据失败:', response);
      ElMessage.warning('获取消息数据失败');
      return false;
    }
  } catch (error) {
    console.error('获取消息数据出错:', error);
    ElMessage.error('获取消息数据出错');
    return false;
  } finally {
    loading.value = false;
  }
}

// 获取通知设置
const fetchSettings = async () => {
  const locationId = getFirstLocationId();
  
  if (!locationId) {
    console.warn('无法获取位置ID，无法获取通知设置');
    return;
  }
  
  try {
    const response = await messagesApi.getLocationSettings(locationId);
    
    if (response && response.code === 200 && response.data && response.data.notification_settings) {
      notificationSettings.value = { ...response.data.notification_settings };
    } else {
      console.warn('获取通知设置失败:', response);
    }
  } catch (error) {
    console.error('获取通知设置失败:', error);
  }
}
</script>

<style scoped>
.apple-notifications-container {
  height: 100%;
  padding: 24px;
  overflow: auto;
}

.apple-page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  border-radius: 16px;
  margin-bottom: 24px;
}

.apple-page-header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: var(--apple-text-primary-light);
}

.dark-mode .apple-page-header h1 {
  color: var(--apple-text-primary-dark);
}

.header-actions {
  display: flex;
  gap: 12px;
}

.apple-tab-container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 100px);
}

.apple-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.apple-tab {
  padding: 12px 20px;
  border-radius: 12px;
  background-color: var(--apple-button-light);
  color: var(--apple-text-primary-light);
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.dark-mode .apple-tab {
  background-color: var(--apple-button-dark);
  color: var(--apple-text-primary-dark);
}

.apple-tab.active {
  background: linear-gradient(135deg, var(--apple-blue), #0062cc);
  color: white;
  box-shadow: 0 4px 12px rgba(0, 122, 255, 0.3);
}

.dark-mode .apple-tab.active {
  background: linear-gradient(135deg, var(--apple-blue-dark), #0A84FF);
  box-shadow: 0 4px 12px rgba(10, 132, 255, 0.3);
}

.tab-badge {
  background-color: #FF3B30;
  color: white;
  width: 22px;
  height: 22px;
  border-radius: 11px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.dark-mode .tab-badge {
  background-color: #FF453A;
}

.apple-tab-content {
  flex: 1;
  border-radius: 16px;
  padding: 24px;
  overflow: auto;
}

.tab-pane {
  height: 100%;
}

.empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--apple-text-secondary-light);
}

.dark-mode .empty-state {
  color: var(--apple-text-secondary-dark);
}

.empty-icon {
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-message {
  font-size: 16px;
}

/* 弹窗样式 */
.apple-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(5px);
}

.modal-container {
  position: relative;
  width: 90%;
  max-width: 500px;
  border-radius: 16px;
  overflow: hidden;
  animation: modalAppear 0.3s ease;
}

@keyframes modalAppear {
  from {
    opacity: 0;
    transform: scale(0.9);
  }

  to {
    opacity: 1;
    transform: scale(1);
  }
}

.modal-header {
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--apple-border-light);
}

.dark-mode .modal-header {
  border-bottom: 1px solid var(--apple-border-dark);
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--apple-text-secondary-light);
}

.dark-mode .close-button {
  color: var(--apple-text-secondary-dark);
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  border-top: 1px solid var(--apple-border-light);
}

.dark-mode .modal-footer {
  border-top: 1px solid var(--apple-border-dark);
}

.settings-section {
  margin-bottom: 24px;
}

.settings-section h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: var(--apple-text-primary-light);
}

.dark-mode .settings-section h3 {
  color: var(--apple-text-primary-dark);
}

.settings-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

/* 苹果风格的复选框 */
.apple-checkbox {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-bottom: 8px;
  width: calc(50% - 8px);
}

.apple-checkbox input[type="checkbox"] {
  appearance: none;
  -webkit-appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 5px;
  border: 2px solid var(--apple-blue);
  margin-right: 10px;
  position: relative;
  cursor: pointer;
  outline: none;
  transition: all 0.2s ease;
}

.dark-mode .apple-checkbox input[type="checkbox"] {
  border-color: var(--apple-blue-dark);
}

.apple-checkbox input[type="checkbox"]:checked {
  background-color: var(--apple-blue);
}

.dark-mode .apple-checkbox input[type="checkbox"]:checked {
  background-color: var(--apple-blue-dark);
}

.apple-checkbox input[type="checkbox"]:checked::after {
  content: '';
  position: absolute;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  top: 2px;
  left: 6px;
  transform: rotate(45deg);
}

.checkbox-label {
  font-size: 14px;
  color: var(--apple-text-primary-light);
}

.dark-mode .checkbox-label {
  color: var(--apple-text-primary-dark);
}

/* 媒体查询适配移动设备 */
@media (max-width: 768px) {
  .apple-page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .apple-tabs {
    width: 100%;
  }

  .apple-tab {
    flex: 1;
    justify-content: center;
  }

  .settings-options {
    flex-direction: column;
  }

  .apple-checkbox {
    width: 100%;
  }
}
</style>